from rest_framework.generics import ListAPIView, ListCreateAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from article.models import Article, Channel

from article.serializers.article import ArticleSerializer, LabelSerializer, ArticalSearchSerializer

#  /channels/
from questions.models import Label


class ArticleViewSet(ListAPIView):
    serializer_class = ArticleSerializer
    queryset = Article.objects.all()

    def list(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            data = serializer.data[0]
            if request.user.id in data['collected_users']:
                collected = True
            else:
                collected = False
            data['collected'] = collected
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        return Response(serializer.data)



class LabelShowViewSet(ListAPIView):
    queryset = Label.objects.all()
    serializer_class = LabelSerializer
    pagination_class = None


class ArticlePostViewSet(APIView):

    def post(self, request):
        user = request.user
        data = request.data
        article = Article()
        article.user = request.user
        article.channel = Channel.objects.get(id = data['channel'])
        article.content = data['content']
        article.title = data['title']
        article.image = data.get('image','')
        article.save()

        for label_id in data['labels']:
            label = Label.objects.get(id = label_id)
            article.labels.add(label)
        article.save()

        return Response({
            "articleid": article.id,
            "message": "OK",
            "success": True
        })


class ArticlaSearchViewSet(ListAPIView):
    serializer_class = ArticalSearchSerializer

    def list(self, request, *args, **kwargs):
        text = request.query_params.get('text')
        queryset = Article.objects.filter(title__contains=text)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)








